package com.seveneight.baijiesteward.ui.main.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Looper;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.flyco.dialog.listener.OnBtnClickL;
import com.flyco.dialog.widget.NormalDialog;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.seveneight.baijiesteward.R;
import com.seveneight.baijiesteward.base.BaseFragment;
import com.seveneight.baijiesteward.base.MessageBean;
import com.seveneight.baijiesteward.base.MessageEvent;
import com.seveneight.baijiesteward.bean.UserBean;
import com.seveneight.baijiesteward.bean.VersionBean;
import com.seveneight.baijiesteward.http.AppConfig;
import com.seveneight.baijiesteward.ui.first.contract.VersionUpdateContract;
import com.seveneight.baijiesteward.ui.first.presenter.VersionUpdatePresenter;
import com.seveneight.baijiesteward.ui.main.activity.LoginActivity;
import com.seveneight.baijiesteward.ui.main.activity.PerfectRepaymentActivity;
import com.seveneight.baijiesteward.ui.main.activity.WebActivity;
import com.seveneight.baijiesteward.ui.user.activity.ManagerCardActivity;
import com.seveneight.baijiesteward.ui.user.contract.UploadHeadContract;
import com.seveneight.baijiesteward.ui.first.fragment.DrawingFragment;
import com.seveneight.baijiesteward.ui.user.fragment.IdentifyFragment;
import com.seveneight.baijiesteward.ui.user.fragment.ManagerAccountFragment;
import com.seveneight.baijiesteward.ui.user.fragment.SettingFragment;
import com.seveneight.baijiesteward.ui.user.fragment.UpgradeFragment;
import com.seveneight.baijiesteward.ui.user.fragment.UserInfoFragment;
import com.seveneight.baijiesteward.ui.user.fragment.PayBackFragment;
import com.seveneight.baijiesteward.ui.user.presenter.UploadHeadPresenter;
import com.seveneight.baijiesteward.utils.AppUtil;
import com.seveneight.baijiesteward.utils.GlideLoader;
import com.seveneight.baijiesteward.utils.HttpUpload;
import com.seveneight.baijiesteward.utils.LogUtil;
import com.seveneight.baijiesteward.utils.PicassoImageLoader;
import com.seveneight.baijiesteward.utils.StringFormat;
import com.seveneight.baijiesteward.utils.TabSelectedEvent;
import com.seveneight.baijiesteward.utils.WindowUtil;
import com.seveneight.baijiesteward.views.CustomerDialog;
import com.seveneight.baijiesteward.views.UpdateDialog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.io.File;
import java.util.ArrayList;

import de.hdodenhof.circleimageview.CircleImageView;
import me.yokeyword.eventbusactivityscope.EventBusActivityScope;

/**
 * Created by user1 on 2018/2/6.
 */

public class UserFragment extends BaseFragment implements UploadHeadContract.UploadHeadView {

    UploadHeadContract.UploadPresenter uploadPresenter;
    private TextView tv_upgrade;
    private LinearLayout layout_userinfo;
    private LinearLayout layout_managercard;
    private TextView tv_account;
    private LinearLayout layout_setting;
    private CircleImageView ci_head;
    private TextView tv_realname;
    private TextView tv_phone;
    private ImagePicker imagePicker;
    private ArrayList<ImageItem> images = null;
    private TextView tv_userlevel;
    private String path;
    private int SUCCESS_CODE = 3;
    private int FAIL_CODE = 4;
    private TextView tv_agreement;
    private String uploadUrl;
    private LinearLayout layout_customer;
    private CustomerDialog customerDialog;
    private TextView tv_rebackMoney;
    private TextView tv_repayaccount;
    private TextView tv_update;
    private TextView tv_versionname;
    private LinearLayout layout_operamanual;
    private UpdateDialog updateDialog;
    private VersionBean versionBean;


    @Override
    protected int getContentView() {
        return R.layout.fragment_user;
    }

    public static UserFragment newInstance() {
        Bundle args = new Bundle();
        UserFragment fragment = new UserFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected void initView() {
        tv_upgrade = findView(R.id.tv_upgrade);
        ci_head = findView(R.id.ci_userhead);
        tv_realname = findView(R.id.tv_realname);
        tv_phone = findView(R.id.tv_phone);
        tv_userlevel = findView(R.id.tv_userlevel);
        layout_userinfo = findView(R.id.layout_userinfo);
        LinearLayout layout_agententrance = findView(R.id.layout_agententrance);
        layout_managercard = findView(R.id.layout_managercard);
        layout_operamanual = findView(R.id.layout_operamanual);
        layout_customer = findView(R.id.layout_customer);
        layout_setting = findView(R.id.layout_setting);
        tv_account = findView(R.id.tv_account);
        tv_repayaccount = findView(R.id.tv_repayaccount);
        tv_rebackMoney = findView(R.id.tv_rebackMoney);
        tv_update = findView(R.id.tv_update);
        tv_versionname = findView(R.id.tv_versionname);
        tv_agreement = findView(R.id.tv_agreement);
        EventBusActivityScope.getDefault(_mActivity).register(this);
    }

    @Override
    protected void initData() {
//        EventBus.getDefault().register(this);
        uploadPresenter = new UploadHeadPresenter(this);
        imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new PicassoImageLoader());
        imagePicker.setShowCamera(true);
        imagePicker.setMultiMode(false);
        imagePicker.setCrop(true);
        imagePicker.setSaveRectangle(true);
        imagePicker.setFocusWidth(800);   //裁剪框的宽度。单位像素（圆形自动取宽高最小值）
        imagePicker.setFocusHeight(800);  //裁剪框的高度。单位像素（圆形自动取宽高最小值）
        imagePicker.setOutPutX(1000);//保存文件的宽度。单位像素
        imagePicker.setOutPutY(1000);//保存文件的高度。单位像素
    }

    @Override
    protected void setListener() {
        layout_operamanual.setOnClickListener(loginclickListener);
        tv_update.setOnClickListener(loginclickListener);
        tv_rebackMoney.setOnClickListener(authClickListener);
        layout_customer.setOnClickListener(loginclickListener);
        tv_agreement.setOnClickListener(loginclickListener);
        tv_upgrade.setOnClickListener(authClickListener);
        layout_userinfo.setOnClickListener(loginclickListener);
        layout_managercard.setOnClickListener(authClickListener);
        tv_account.setOnClickListener(loginclickListener);
        layout_setting.setOnClickListener(loginclickListener);
        ci_head.setOnClickListener(loginclickListener);
        tv_realname.setOnClickListener(loginclickListener);
        tv_repayaccount.setOnClickListener(authClickListener);
        findView(R.id.layout_card).setOnClickListener(loginclickListener);
    }

    @Override
    public void BusCall(MessageEvent messageEvent) {
        super.BusCall(messageEvent);
        if (messageEvent.getType()==120){
            ((MainFragment) getParentFragment()).startBrotherFragment(ManagerAccountFragment.newInstance());
        }else if (messageEvent.getType()==121){
            ((MainFragment) getParentFragment()).startBrotherFragment(UpgradeFragment.newInstance());
        }
    }

    //登录即可使用的功能
    View.OnClickListener loginclickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (!setting.isLogin()) {
                WindowUtil.getInstance().startUpActivity(getActivity(), LoginActivity.class);
                return;
            }
            switch (v.getId()) {
                case R.id.layout_card:
                    startActivity(new Intent(getContext(),PerfectRepaymentActivity.class));
                    break;
                case R.id.tv_agreement:
                    Bundle bundle2 = new Bundle();
                    bundle2.putString("url", AppConfig.RULE);
                    WindowUtil.getInstance().startActivity(mContext, WebActivity.class, bundle2);
                    break;
                case R.id.layout_customer:
                    if (customerDialog == null) {
                        customerDialog = new CustomerDialog(mContext);
                    }
                    customerDialog.show();
                    break;
                case R.id.layout_setting:
                    ((MainFragment) getParentFragment()).startBrotherFragment(SettingFragment.newInstance());
                    break;
                case R.id.tv_account:
                    ((MainFragment) getParentFragment()).startBrotherFragment(ManagerAccountFragment.newInstance());
                    break;
                case R.id.layout_userinfo:
                    ((MainFragment) getParentFragment()).startBrotherFragment(UserInfoFragment.newInstance());
                    break;
                case R.id.tv_realname:
                    ((MainFragment) getParentFragment()).startBrotherFragment(IdentifyFragment.newInstance());
                    break;
                case R.id.ci_userhead:
                    Intent intent = new Intent(mContext, ImageGridActivity.class);
                    intent.putExtra(ImageGridActivity.EXTRAS_IMAGES, images);
                    startActivityForResult(intent, 100);
                    break;
                case R.id.tv_update:
                    new VersionUpdatePresenter(new VersionUpdateContract.VersionUpdateView() {
                        @Override
                        public void rebackVersionInfo(VersionBean versionBean) {
                            if (updateDialog == null) {
                                updateDialog = new UpdateDialog(getActivity());
                            }
                            if (versionBean.getVersionCode() > AppUtil.getselfVersionCode(mContext)) {
                                updateDialog.needUpdateDialog(versionBean);
                            } else {
                                updateDialog.noUpdateDialog();
                            }
                        }
                    }).getVersionInfo();
//                    if (updateDialog == null) {
//                        updateDialog = new UpdateDialog(getActivity());
//                    }
//                    versionBean = setting.getVersion();
//                    if (versionBean.getVersionCode() > AppUtil.getselfVersionCode(mContext)) {
//                        updateDialog.needUpdateDialog(versionBean);
//                    } else {
//                        updateDialog.noUpdateDialog();
//                    }
                    break;
                case R.id.layout_operamanual:
                    Bundle bundle3 = new Bundle();
                    bundle3.putString("url", AppConfig.OPERATE_BOOK);
                    WindowUtil.getInstance().startActivity(mContext, WebActivity.class, bundle3);
                    break;

            }
        }
    };

    //实名后才能用的功能
    View.OnClickListener authClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (!setting.isLogin()) {
                WindowUtil.getInstance().startUpActivity(getActivity(), LoginActivity.class);
                return;
            }
            if (setting.getUserInfo().getAuthStatus().equals("-1")) {
                showDialog("实名审核中，请稍后再试");
                return;
            }

            if (!setting.getUserInfo().getAuthStatus().equals("1")) {
                showIdentifyDialog();
                return;
            }
            switch (v.getId()) {
                case R.id.tv_upgrade:
                    ((MainFragment) getParentFragment()).startBrotherFragment(UpgradeFragment.newInstance());
                    break;
                case R.id.layout_managercard:
//                ((MainFragment) getParentFragment()).startBrotherFragment(ManagercardFragment.newInstance());
                    Bundle bundle = new Bundle();
                    bundle.putInt("type", 0);
                    WindowUtil.getInstance().startActivity(mContext, ManagerCardActivity.class, bundle);
                    break;
                case R.id.tv_rebackMoney:
                    ((MainFragment) getParentFragment()).startBrotherFragment(DrawingFragment.newInstance());
                    break;
                case R.id.tv_repayaccount:
//                    ((MainFragment) getParentFragment()).startBrotherFragment(PayBackFragment.newInstance());
                    if (userBean.getIsSetTradePassword()){
                        ((MainFragment) getParentFragment()).startBrotherFragment(PayBackFragment.newInstance());
                    }else {
                        showDialog();
                    }
                    break;
            }
        }
    };
    public void showDialog(){
        new MaterialDialog.Builder(getContext())
                .title("设置提醒")
                .titleColorRes(R.color.graytext)
                .content("请先设置交易密码")
                .contentColorRes(R.color.graytext)
                .backgroundColorRes(R.color.white)
                .negativeColorRes(R.color.mainblue)
                .negativeText(R.string.negative)
                .positiveColorRes(R.color.mainblue)
                .positiveText(R.string.positive)
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        ((MainFragment) getParentFragment()).startBrotherFragment(ManagerAccountFragment.newInstance());
                    }
                })
                .build().show();
    }


    @Override
    public void uploadStatus() {
        setting.setHeadImgUrl(uploadUrl);
        initUI();
    }

    /**
     * Reselected Tab
     */
    @Subscribe
    public void onTabSelectedEvent(TabSelectedEvent event) {
        if (event.position != MainFragment.FIRST) return;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
//        EventBus.getDefault().unregister(this);
    }

    @Subscribe
    public void onEvent(MessageEvent messageEvent) {
        switch (messageEvent.getType()) {
            case 1:
                initUI();
                break;
        }
    }

    @Subscribe
    public void onEvent(MessageBean bean) {
        switch (bean.getType()) {
            case 3:
                LogUtil.d("收到成功消息");
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        hideLoading();
                        uploadUrl = (String) bean.getData();
                        LogUtil.d("uploadUrl:" + uploadUrl);
                        uploadPresenter.uploadHeadImg(mContext, jsonFormat.updateHead(uploadUrl));
                    }
                });
                break;
            case 4:
                hideLoading();
                LogUtil.d("收到失败消息" + bean.getData());
                Looper.prepare();
                showDialog((String) bean.getData());
                Looper.loop();
                break;
        }
    }

    private void initUI() {
        tv_versionname.setText("v" + AppUtil.getselfVersionName(mContext));
        if (setting.isLogin()) {
//            UserBean userBean = setting.getUserInfo();
            if (userBean==null){
                userBean = setting.getUserInfo();
            }
            tv_phone.setText(StringFormat.getPhoneNumber(userBean.getMobilePhone()));
            if (userBean.getAuthStatus().equals("0")) {
                tv_realname.setText("实名认证");
                tv_realname.setEnabled(true);
            } else if (userBean.getAuthStatus().equals("-1")) {
                tv_realname.setText("审核中");
                tv_realname.setEnabled(false);
            } else if (userBean.getAuthStatus().equals("1")) {
                tv_realname.setText("已认证");
                tv_realname.setEnabled(false);
            } else {
                tv_realname.setText("审核失败");
                tv_realname.setEnabled(true);
            }
            if (!TextUtils.isEmpty(setting.getHeadImgUrl())) {
                GlideLoader.displayImg(mContext, setting.getHeadImgUrl(), ci_head);
            } else {
                GlideLoader.displayImg(mContext, R.mipmap.user_head, ci_head);
            }
        } else {
            tv_realname.setText("实名认证");
            tv_realname.setEnabled(true);
            tv_phone.setText("未登录");
            tv_userlevel.setText("");
            GlideLoader.displayImg(mContext, R.mipmap.user_head, ci_head);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        LogUtil.d("!onResume");
        initUI();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null && requestCode == 100) {
            images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
            path = images.get(0).path;
            uploadHead();
        }
    }

    private void uploadHead() {
        showLoading("正在上传头像");
        HttpUpload upload = new HttpUpload(setting.getUserID(), 0, path, SUCCESS_CODE, FAIL_CODE);
        upload.startUpload();
    }

    public void showIdentifyDialog() {
        NormalDialog dialog = new NormalDialog(mContext);
        dialog.content("请进行实名认证")//
                .style(NormalDialog.STYLE_TWO)//
                .titleTextSize(18)//
                .show();

        dialog.setOnBtnClickL(
                new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        dialog.dismiss();
                    }
                },
                new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        ((MainFragment) getParentFragment()).startBrotherFragment(IdentifyFragment.newInstance());
                        dialog.dismiss();
                    }
                });
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            initUI();
        }
    }
}
